import React, { FC, useState, useEffect } from 'react'
import { Form, Button, Modal, DatePicker, message } from 'antd'
import { InfoCircleOutlined } from '@ant-design/icons'
import SuccessModal from '~/components/submit-successfully'
import { getUserInfo } from '~/mock/user/userinfo'
import TopHeader, { ListTitle } from '~/components/top-header'
import { formatTime } from '~/utils/utils'
import moment from 'moment'
import {
  queryWaitCastItems,
  queryCastItems,
  handleTransfer,
  handleMakeUp,
  handleAcquireTime
} from '~/api/transfer-property-api'

import WaitingList from './container/waiting-list'
import MovedList from './container/moved-list'
import AddInformation from '../components/add-information'
import { FooterAction } from './styled'
import { useNavigate, useLocation } from 'react-router-dom'

const PropertyInvolved: FC = () => {
  const [form] = Form.useForm()
  const { state }: any = useLocation()
  const navigate = useNavigate()
  const [makeUpVisible, setMakeUpVisible] = useState(false)
  const [makeUpData, setMakeUpData] = useState<any>({})
  const [successVisible, setSuccessVisible] = useState(false)
  const [exeTimeVisible, setExeTimeVisible] = useState(false)
  const [seriesNos, setSeriesNos] = useState([])
  const [waitCastItems, setWaitCastItems] = useState([])
  const { validateFields } = form

  const { caseCompanyName, caseDepartmentName, caseName, caseNo, createTime, caseState, batchNo } = state

  const onClickTransfer = async () => {
    if (!seriesNos.length) {
      return message.error('请至少选择一个物品')
    }
    const newLatestData = waitCastItems.filter((item: any) => seriesNos.find((subItem: any) => subItem.id === item.id))
    if (newLatestData.filter((item: any) => !item.acquireTime).length) {
      return message.error('请补全执行时间')
    }
    const userInfo = getUserInfo()
    await handleTransfer({
      ...userInfo,
      serialNos: seriesNos.map((item: any) => item.serialNo)
    })
    setSuccessVisible(true)
  }

  const handleGetueryWaitCastItems = async () => {
    const userInfo = getUserInfo()
    const { data } = await queryWaitCastItems({
      ...userInfo,

      caseName,
      caseNo,
      itemOptType: 'TRANSFER'
    })
    setWaitCastItems(data)
  }

  const handleHadCastItems = async () => {
    const userInfo = getUserInfo()
    const { data } = await queryCastItems({
      ...userInfo,
      batchNo,
      statusList: ['WAIT', 'FAIL', 'SUCCESS']
    })
    setWaitCastItems(data)
  }

  const handleCastItems = () => {
    if (caseState === 1 || caseState === 2) {
      handleGetueryWaitCastItems()
    } else {
      handleHadCastItems()
    }
  }

  const handleMakeUpClick = async (val: any) => {
    await handleMakeUp({ ...val, caseName, caseNo, serialNo: makeUpData.serialNo })
    await handleCastItems()
  }

  const onClickAcuqireTime = async () => {
    const { acquireTime } = await validateFields(['acquireTime'])
    const userInfo = getUserInfo()
    await handleAcquireTime({
      ...userInfo,
      acquireTime: acquireTime && moment(acquireTime).format(),
      serialNos: seriesNos.map((item: any) => item.serialNo)
    })
    handleGetueryWaitCastItems()
    setExeTimeVisible(false)
  }

  useEffect(() => {
    handleCastItems()
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [])

  const headData = [
    {
      childen: [
        {
          label: '案件编号:',
          value: caseNo
        },
        { label: '案件名称:', value: caseName }
      ]
    },
    {
      childen:
        caseState !== 1
          ? [
              { label: '移交时间:', value: formatTime(createTime) },
              { label: '批次号:', value: batchNo }
            ]
          : [
              { label: '办案单位:', value: caseCompanyName },
              { label: '办案部门:', value: caseDepartmentName }
            ]
    }
  ]

  return (
    <div>
      <TopHeader headData={headData} />
      <ListTitle />
      <main style={{ marginTop: 21 }}>
        {/* <Form layout="inline" form={form} style={{ marginBottom: 16 }}>
          <Form.Item name="1" label="案件编号：">
            <Input placeholder="请输入案件编号搜索" />
          </Form.Item>
          <Form.Item name="2" label="案件名称：">
            <Input placeholder="请输入案件名称搜索" />
          </Form.Item>
          <Form.Item>
            <Button onClick={() => resetFields()} type="link" style={{ padding: 0 }}>
              清空选项
            </Button>
          </Form.Item>
        </Form> */}
        {caseState === 1 ? (
          <WaitingList
            waitCastItems={waitCastItems}
            setMakeUpData={setMakeUpData}
            setMakeUpVisible={setMakeUpVisible}
            setSeriesNos={setSeriesNos}
            seriesNos={seriesNos}
          />
        ) : (
          <MovedList waitCastItems={waitCastItems} />
        )}
        <FooterAction>
          <div>
            <Button
              onClick={() => {
                navigate(-1)
              }}
            >
              返回
            </Button>
            {state.caseState === 3 ? null : (
              <Button
                onClick={() => {
                  if (!seriesNos.length) {
                    return message.error('请至少选择一个物品')
                  }
                  if (seriesNos.filter((item: any) => item.acquireTime).length) {
                    return message.error('已有执行时间行不可修改')
                  }
                  setExeTimeVisible(true)
                }}
                style={{ marginLeft: 8 }}
              >
                采集执行时间
              </Button>
            )}

            {state.caseState === 1 || state.caseState === 2 ? (
              <Button onClick={onClickTransfer} style={{ marginLeft: 8 }} type="primary">
                移送专管员
              </Button>
            ) : null}
          </div>
        </FooterAction>
        <AddInformation
          setMakeUpVisible={setMakeUpVisible}
          makeUpData={makeUpData}
          visible={makeUpVisible}
          onCreate={val => {
            console.log('val', val)
            setMakeUpVisible(false)
            handleMakeUpClick(val)
          }}
          onCancel={() => {
            setMakeUpVisible(false)
            console.log('222')
          }}
        />
        <SuccessModal visible={successVisible} />
        <Modal
          width={690}
          title="批量采集执行时间"
          visible={exeTimeVisible}
          onCancel={() => {
            setExeTimeVisible(false)
          }}
          footer={null}
        >
          <Form validateTrigger="onBlur" form={form}>
            <Form.Item
              name="acquireTime"
              rules={[{ required: true, message: '请选择采集执行时间' }]}
              label="采集执行时间"
            >
              <DatePicker showTime={{ format: 'HH:mm' }} style={{ width: 237 }} />
            </Form.Item>
          </Form>
          <div style={{ display: 'flex', justifyContent: 'flex-end', alignItems: 'center' }}>
            <InfoCircleOutlined style={{ color: '#3370da', fontSize: 14 }} />
            <span style={{ marginLeft: 7 }}>请注意！执行时间采集完成后不能修改</span>
            <Button
              style={{ marginLeft: 14 }}
              onClick={() => {
                setExeTimeVisible(false)
              }}
            >
              取消
            </Button>
            <Button onClick={onClickAcuqireTime} style={{ marginLeft: 8 }} type="primary">
              确认
            </Button>
          </div>
        </Modal>
      </main>
    </div>
  )
}

export default PropertyInvolved
